package com.example.service;

import cn.hutool.core.lang.UUID;
import com.example.ccubee.common.exception.DemoException;
import com.example.contant.RedisKeyConstant;
import com.example.entity.SkillGoods;
import com.example.entity.SkillOrder;
import com.example.mapper.SkillGoodsMapper;
import com.example.mapper.SkillOrderMapper;
import com.example.utils.RedisLock;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * @author ccubee
 * @since 2021/8/26 19:54
 */
@Service
@RequiredArgsConstructor
public class TestService {

    private final SkillGoodsMapper skillGoodsMapper;
    private final SkillOrderMapper skillOrderMapper;
    private final RedisLock redisLock;
    private final SkillGoodsService skillGoodsService;

    private static final int TIMEOUT = 10 * 1000; // 10秒钟

    public void test(String userId, Long productId) {
        userId = UUID.fastUUID().toString(true);

        // 下单
        long time = System.currentTimeMillis() + TIMEOUT;
        boolean isLock = redisLock.lock(productId+"", String.valueOf(time));
        if (!isLock) {
            throw new DemoException("人也太多了 换个姿势试试~~");
        }
        SkillGoods skillGoods = skillGoodsMapper.selectById(productId);
        if (0 == skillGoods.getStockCount()) {
            throw new DemoException("已卖完");
        } else {
            SkillOrder order = SkillOrder.builder()
                    .skillId(productId)
                    .userId(userId)
                    .createTime(LocalDateTime.now())
                    .build();
            skillOrderMapper.insert(order);
            skillGoodsService.test(skillGoods);
        }
       redisLock.unLock(productId+"", String.valueOf(time));

    }
}
